import React, { Component } from 'react';
import { Modal, Alert, Popover, Input, Table, InputNumber, Button, message } from 'antd'
import { deepFullCopy, messages, queryCurrencyPrecision } from "share/common"
import moment from "moment"
import corporatePaymentReportService from 'containers/corporate-payment-report/corporate-payment-report.service'
import { openModal, removeContainer } from "components/method/openModal"

class PayWriteOffModal extends Component {

  onSelectChange = selectedRowKeys => {
    let { rowSelection } = this.state;
    rowSelection.selectedRowKeys = selectedRowKeys;
    this.setState({ rowSelection });
  };

  onSelectItem = (record, selected) => {
    let { showData, writeOffAmount } = this.state;
    if (selected) {
      showData = showData.map(item => {
        if (item.transactionId === record.transactionId) {
          item.writeOffAmount = Math.min(this.baseAmount - writeOffAmount + item.writeOffAmount, item.enableWriteOffAmount);
        }
        return item
      })
    } else {
      showData = showData.map(item => {
        if (item.transactionId === record.transactionId) {
          item.writeOffAmount = 0;
        }
        return item
      })
    }
    this.setState({ showData }, this.refreshHead)
  };

  onSelectAll = (selected, selectedRows, changeRows) => {
    let { showData } = this.state;
    let writeOffAmount = deepFullCopy(this.state.writeOffAmount);
    if (selected) {
      changeRows.forEach(record => {
        showData = showData.map(item => {
          if (item.transactionId === record.transactionId) {
            let changeValue = Math.min(this.baseAmount - writeOffAmount + item.writeOffAmount, item.enableWriteOffAmount) - item.writeOffAmount;
            item.writeOffAmount += changeValue;
            writeOffAmount += changeValue;
          }
          return item
        })
      });
    } else {
      changeRows.forEach(record => {
        showData = showData.map(item => {
          if (item.transactionId === record.transactionId) {
            item.writeOffAmount = 0;
          }
          return item
        })
      });
    }
    this.setState({ showData }, this.refreshHead)
  };

  state = {
    loading: false,
    saveLoading: false,
    pagination: {
      total: 0,
      defaultPageSize: 5
    },
    data: [],
    showData: [],
    rowSelection: {
      type: 'checkbox',
      onChange: this.onSelectChange,
      onSelect: this.onSelectItem,
      onSelectAll: this.onSelectAll
    },
    writeOffAmount: 0,
    realPaymentAmount: 0
  };

  baseAmount = this.props.payInfoDetail.invoiceViewDTO.amount - this.props.payInfoDetail.planedAmount;

  componentDidMount () {
    const { expenseInfo, payInfoDetail } = this.props;
    this.setState({ loading: true });
    let params = {
      companyOID: expenseInfo.docCompanyOID,
      payeeId: expenseInfo.corpSupplierId,
      payeeType: 1001,
      currencyCode: expenseInfo.currencyCode,
      setOfBooksId: expenseInfo.setOfBooksId,
      expenseReportOID: expenseInfo.expenseReportOID,
      expenseTypeOID: payInfoDetail.invoiceViewDTO.expenseTypeOID
    };
    payInfoDetail.id && (params.paymentScheduleId = payInfoDetail.id);
    corporatePaymentReportService.getWriteOffList(params).then(res => {
      const { rowSelection } = this.state;
      rowSelection.selectedRowKeys = (payInfoDetail.writeOffCommandList || []).map(item => item.transactionId);
      let baseData = res.data.map(record => {
        let temp = (payInfoDetail.writeOffCommandList || []).find(item => item.transactionId === record.transactionId);
        temp && (record.writeOffAmount = temp.writeOffAmount);
        return record;
      });
      this.setState({
        data: baseData,
        showData: baseData,
        loading: false,
        rowSelection
      }, this.refreshHead);
    }).catch(e => {
      this.setState({ loading: false });
      message.error(e.response.data.message);
    })
  }

  handleOnChange = (value, transactionId) => {
    let { showData, rowSelection, realPaymentAmount } = this.state;
    showData = showData.map(item => {
      if (item.transactionId === transactionId) {
        if (value - item.writeOffAmount > realPaymentAmount) {
          item.writeOffAmount += realPaymentAmount;
        } else {
          item.writeOffAmount = value
        }
      }
      return item
    });
    value && rowSelection.selectedRowKeys.addIfNotExist(transactionId);
    this.setState({ showData, rowSelection }, this.refreshHead);
  };

  refreshHead = () => {
    const { showData } = this.state;
    let writeOffAmount = 0;
    showData.forEach(item => writeOffAmount += item.writeOffAmount);
    let realPaymentAmount = this.baseAmount - writeOffAmount;
    this.setState({ writeOffAmount, realPaymentAmount })
  };

  columns = [
    {
      title: messages('expense-1.key39')/*交易日期*/, dataIndex: 'payDate',
      render: value => value ? moment(value).format('YYYY-MM-DD') : '-'
    },
    {
      title: messages('finance-9.key8')/*对公支付单号*/, dataIndex: 'businessCode',
      render: value => <Popover content={value} placement={'topLeft'}>{value}</Popover>
    },
    { title: messages('finance-9.key15')/*预付类型*/, dataIndex: 'prepaymentTypeName' },
    {
      title: messages('finance-9.key2')/*事由*/, dataIndex: 'remark',
      render: value => <Popover content={value} placement='topLeft'>{value}</Popover>
    },
    {
      title: messages('common.department')/*部门*/,
      dataIndex: 'departmentName',
      render: value => <Popover content={value} placement='topLeft'>{value}</Popover>
    },
    { title: messages('common.currency')/*币种*/, dataIndex: 'currencyCode', width: 48 },
    {
      title: messages('common.total.amount')/*总金额*/,
      dataIndex: 'amount',
      render: (value, record) => this.filterMoney(value, queryCurrencyPrecision(record.currencyCode))
    },
    {
      title: messages('expense-1.key575')/*可核销金额*/,
      dataIndex: 'enableWriteOffAmount',
      render: (value, record) => this.filterMoney(value, queryCurrencyPrecision(record.currencyCode))
    },
    {
      title: messages('expense-1.key567')/*本次核销额*/,
      dataIndex: 'writeOffAmount',
      width: 150,
      render: (value, record) => {
        return (
          <InputNumber
            className="no-input-style"
            style={{width: '100%'}}
            onChange={value => this.handleOnChange(value, record.transactionId)}
            min={0}
            value={value}
            max={record.enableWriteOffAmount}
            precision={queryCurrencyPrecision(record.currencyCode)}
          />
        )
      }
    }
  ];

  clearSelect = () => {
    let { showData, rowSelection } = this.state;
    rowSelection.selectedRowKeys = [];
    showData = showData.map(item => {
      item.writeOffAmount = 0;
      return item;
    });
    this.setState({ showData, rowSelection }, this.refreshHead)
  };

  handleOk = () => {
    const { onOk } = this.props, { showData } = this.state;
    onOk(showData.filter(item => item.writeOffAmount).map(item => ({
      transactionId: item.transactionId,
      prepaymentLineId: item.id,
      writeOffAmount: item.writeOffAmount,
      businessCode: item.businessCode,
      prepaymentTypeName: item.prepaymentTypeName
    })))
  };

  handleChangeKey = e => {
    let value = e.target.value;
    const { showData } = this.state;
    this.setState({
      data: value
        ? showData.filter(item => item.businessCode.indexOf(value) > -1 || (item.remark || '').indexOf(value) > -1)
        : showData
    })
  };


  render () {
    const { visible, onCancel, payInfoDetail: { invoiceViewDTO } } = this.props;
    const { data, loading, pagination, saveLoading, rowSelection, writeOffAmount, realPaymentAmount } = this.state;
    return (
      <Modal
        visible={visible}
        onCancel={onCancel}
        width={1000}
        title={messages('finance-9.key98')/*核销预付款*/}
        footer={<div>
          <Button onClick={this.clearSelect}>{messages('expense-1.key569')/*清除已选*/}</Button>
          <Button onClick={onCancel}>{messages('common.cancel')/*取消*/}</Button>
          <Button type='primary' onClick={this.handleOk} loading={saveLoading}>{messages('common.ok')/*确定*/}</Button>
        </div>}
      >
        <Alert
          message={(
            <div style={{ marginLeft: '15px' }}>
              <div>{messages('finance-9.key99')/*核销金额不能超过费用总金额*/}</div>
            </div>
          )}
          type="warning"
          showIcon
          style={{ marginBottom: '8px' }}
        />
        <div style={{ fontSize: '16px', fontWeight: '600', lineHeight: '30px' }}>
          {messages('finance-9.key100')/*费用总额*/}：{invoiceViewDTO.currencyCode}&nbsp;&nbsp;
          {this.filterMoney(invoiceViewDTO.amount, queryCurrencyPrecision(invoiceViewDTO.currencyCode))}
        </div>
        <div style={{ marginBottom: '12px', overflow: 'hidden' }}>
          {messages('expense-1.key574')/*已核销金额*/}：
          {invoiceViewDTO.currencyCode}&nbsp;&nbsp;
          {this.filterMoney(writeOffAmount, queryCurrencyPrecision(invoiceViewDTO.currencyCode))}
          &nbsp;&nbsp;&nbsp;&nbsp;
          {messages('expense-1.key575')/*可核销金额*/}：
          {invoiceViewDTO.currencyCode}&nbsp;&nbsp;
          {this.filterMoney(realPaymentAmount, queryCurrencyPrecision(invoiceViewDTO.currencyCode))}
          <Input.Search
            style={{ float: 'right', width: '300px' }}
            maxLength='200'
            placeholder={messages('expense-1.key576')/*请输入单号/事由*/}
            onChange={this.handleChangeKey}
          />
        </div>
        <Table
          rowKey="transactionId"
          className={'write-off-table'}
          size={'small'}
          columns={this.columns}
          dataSource={data}
          rowSelection={rowSelection}
          loading={loading}
          pagination={pagination}
          bordered
        />
      </Modal>
    )
  }
}

PayWriteOffModal.open = function(env, params) {
  let container;
  return new Promise(resolve => {
    const targetProps = {
      visible: true,
      onOk: data => close(data),
      onCancel: () => close(null),
      afterClose: () => {
        removeContainer(container);
        container = null;
      },
      ...params
    };
    function close(data) {
      let closeModal = () => openModal(PayWriteOffModal, {
        ...targetProps,
        visible: false
      }, env, container);
      if(data !== null) {
        resolve({data, closeModal});
      }
      else closeModal();
    }
    container = openModal(PayWriteOffModal, targetProps, env);
  })
};

export default PayWriteOffModal
